%%--------------------------------------------------------------------
%% Author: <vjache>
%% Created: 17.03.2009
%% Description: TODO: Add description to merge_sort
%%--------------------------------------------------------------------
-module(iter_filter).

%%--------------------------------------------------------------------
%% Include files
%%--------------------------------------------------------------------
-include("../include/iter.hrl").
%%--------------------------------------------------------------------
%% Exported Functions
%%--------------------------------------------------------------------
-export([
		 new/2,
		 open/1,
		 next/1,
		 close/1,
		 test/1
		 ]).

%%--------------------------------------------------------------------
%% API Functions
%%--------------------------------------------------------------------
new(Iter,FilterPredFun) when is_function(FilterPredFun, 1)->
	iter:from_module(?MODULE, {Iter,FilterPredFun}).
open({Iter,FilterPredFun}) ->
	State=iter:open(Iter),
	{State,FilterPredFun}.

next({State,FilterPredFun}) ->
	{NewState,Item}=iter:next(State),
	case Item of
		?EOF ->
			{{NewState,FilterPredFun},?EOF};
		_ ->
			case FilterPredFun(Item) of
				true ->
					{{NewState,FilterPredFun},Item};
				false ->
					next({NewState,FilterPredFun})
			end
	end.

close({State,_FilterPredFun}) ->
	ok=iter:close(State).

%%--------------------------------------------------------------------
%% Test Functions
%%--------------------------------------------------------------------

test(LL) ->
	I=iter:from_module(?MODULE, [iter:from_list(L)||L<-LL]),
	iter:foreach(I,fun(E)->
						   io:format("~p~n",[E])
				 end),
	ok.

%%--------------------------------------------------------------------
%% Local Functions
%%--------------------------------------------------------------------